<template>
  <div class="app-container">

    <el-form :model="form" ref="form" label-width="160px" v-loading="formLoading" :rules="rules">
    <el-form-item label="项目类别：" prop="courseProject" required>
        <el-select v-model="form.courseProject" placeholder="请选择" @click="getcourseProject">
          <el-option v-for="item in courseprojectlist" :key="item.id" :label="item.concreteName" :value="item.id"></el-option>
        </el-select>
    </el-form-item>

    <el-form-item label="课程名称：" prop="courseName" required>
        <el-input v-model="form.courseName"></el-input>
    </el-form-item>

    <el-form-item label="课程类别：" prop="courseType" required>
        <el-select
         v-model="form.courseType"
         placeholder="课程类别"
         clearable
         :remote-method="getcourseType"
         >
          <el-option
            v-for="item in coursetypelist"
            :key="item.id"
            :value="item.id"
            :label="item.concreteName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="副标题：" prop="subtitle">
        <el-input v-model="form.subtitle"></el-input>
      </el-form-item>
      <el-form-item label="课程概述：" prop="introduction">
        <el-input v-model="form.introduction"></el-input>
      </el-form-item>
      <el-form-item label="课程封面：" required>
        <el-upload
          class="upload-demo"
          action="http://175.24.33.88:8000/api/admin/course/courseCoverUpload"
          :on-preview="handlePreview"
          ref="upload"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :auto-upload="true"
          :http-request="fileUpload"
          :with-credentials="true"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
         <img v-show= imgshow width="40%" height="400px"   :src="'http://175.24.33.88:8001/static'+this.form.coverPath" />
      </el-form-item>
      <!--视频上传-->
      <el-form-item label="添加视频:" prop="subCourseName">
        <el-select
         v-model="data.subCourseName"
         placeholder="请选择"
         filterable clearable
         :remote-method="getvideoName"
         @change="videoChange"
         >
          <el-option
            v-for="item in videoNameList"
              :key="item.id"
              :value="item.id"
              :label="item.subCourseName"
          ></el-option>
        </el-select>
        <el-button @click="addItem" type="text" style="margin-left:20px">新增</el-button>
      </el-form-item>
      <div style="margin-left:120px;margin-bottom:20px">
        <el-table :data="subCourseList" style="width:700px" border>
          <el-table-column prop="subCourseName" label="视频名称" align="center"></el-table-column>
          <el-table-column width="120" label="操作" align="center">
            <template slot-scope="scope">
              <el-button @click="delItem(scope.row)" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>


  </div>
</template>

<script>
import { allCategory,selectCategory,getCategoryPageList,createCategory,deleteCategory} from "@/api/category/category";
import { changeStatus,getVPager,selectCourse,getCoursePageList,createCourse,form} from "@/api/xzs/course";
import { getsubCoursePageList} from "@/api/xzs/subCourse";
import Editor from '@/components/Editor';
import request from '@/utils/request'
export default {
  inject:['reload'],
   components: {
    Editor
  },
  data() {
    return {
      form: {
        id: null,
        courseProject: "",
        courseProjectCategory: 1,
        courseName: "",
        courseType: "",
        courseTypeCategory: 0,
        subtitle: "",
        introduction: "",
        coverPath:"",
        //subCourseName:''
      },
      data:{
        subCourseName:'' ,
      },
      subCourseList:[],
      imgshow:false,
      courseprojectlist:[],
      coursetypelist:[],
      videoNameList:[],
      videoPageList:[],
      //getVideoList:[],
      selVideoPage:null,
      formLoading: false,
      rules: {
         courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    let id = this.$route.query.id
    this.getcourseProject();
    this.getcourseType();
    this.getvideoName();
    let _this = this
     if (id && parseInt(id) !== 0) {
      _this.formLoading = true;
       getVPager(id).then(res => {
        if(res.code === 1){
        _this.subCourseList = res.response;
        //console.log(this.videoPageList);
        _this.formLoading = false;
        }

      });
      selectCourse(id).then(re => {
        this.imgshow=true;
        _this.form.id = re.response.id;
        _this.form.courseName = re.response.courseName;
        _this.form.courseProject = re.response.courseProject;
        _this.form.courseType = re.response.courseType;
        _this.form.subtitle = re.response.subtitle;
        _this.form.introduction = re.response.introduction;
        _this.form.coverPath = re.response.coverPath;

      });
      console.log(id)

    }
  },
  methods: {
    fileUpload(file){
      let files = file.file
      //console.log(file.file)
      let formObj = new FormData();
      formObj.append("uploadFile", files)
       request({
        method: "post",
        url: "/api/admin/course/courseCoverUpload", // 请求地址
        data: formObj, // 参数
        //responseType: "Object", // 表明返回服务器返回的数据类型
        headers: {
          "Content-Type": "application/json"
        }
      }).then(img=> {
         console.log(img);
         this.form.coverPath = img.response;
        //this.form.coverPath = JSON.parse(res.response)
        console.log(this.form.coverPath)
         this.imgshow=true;
      })
    },
    //表格数据参数格式化
    //nameFormatter(row, column, cellValue) {
      //let str = "";
      //this.videoNameList.map(item => {
        //if (item.id == cellValue) {
          //str = item.subCourseName;
        //}
      //});
      //return str;
    //},
    //课程修改
    videoChange(id) {
      this.videoNameList.map(item => {
        if (item.id == id) {
          this.selVideoPage = item;
          return;
        }
      });
    },
      submitForm () {
         let data = {
        id: this.form.id,
        courseProject: this.form.courseProject,
        courseProjectCategory: this.form.courseProjectCategory,
        courseName:this.form.courseName,
        courseType: this.form.courseType,
        courseTypeCategory: this.form.courseTypeCategory,
        subtitle: this.form.subtitle,
        introduction:this.form.introduction,
        coverPath: this.form.coverPath,
        subCourseList: []
      };
      this.subCourseList.map(item => {
        data.subCourseList.push(item.id);
      });
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true
          createCourse(data).then(data => {
            if (data.code === 1) {
              _this.$message.success(data.message)
              _this.$router.push('/courses/courseli/index')

            } else {
              _this.$message.error(data.message)
              _this.formLoading = false
            }
          }).catch(e => {
            _this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    //获取项目类别
    getcourseProject(query) {
      this.formLoading = true;
      getCategoryPageList({
          condition: query,
          categoryId: 1,
          concreteName: "",
          pageNum: 1,
          pageSize: 100
        })
        .then(res => {
          this.formLoading = false;
          console.log(res)
          if (res.code == 1) {
            this.courseprojectlist = res.response.list;
          }
        })
        .catch(res => {
          this.formLoading = false;
        });
    },
    //获取课程类别
    getcourseType(query) {
      this.formLoading = true;
       getCategoryPageList({
          condition: query,
          categoryId: 0,
          concreteName: "",
          pageNum: 1,
          pageSize: 100
        })
        .then(res => {
          this.formLoading = false;
          if (res.code == 1) {
            this.coursetypelist = res.response.list;
          }
        })
        .catch(res => {
          this.formLoading = false;
        });
    },
     //得到视频列表
    getvideoName(query) {
      this.formLoading = true;
      getsubCoursePageList({
          condition: query,
          lecturerName:"",
          subCourseName: this.data.subCourseName,
          pageNum: 1,
          pageSize: 100
        })
        .then(res => {
          this.formLoading = false;
          if (res.code == 1) {
            this.videoNameList = res.response.list;
          }
        })
        .catch(res => {
          this.formLoading = false;
        });
    },
    //添加新记录
    addItem() {
      if (!this.selVideoPage) {
        this.$message({
          showClose: true,
          message: "请先选择视频名称"
        });
      } else {
        //console.log(this.videoPageList)
        this.subCourseList.push({
          //paperType: this.selType.key,
          subCourseName: this.selVideoPage.subCourseName,
          id: this.selVideoPage.id
        });
      }
    },
    //删除记录
    delItem(row) {
      let index = this.subCourseList.findIndex(item => {
        return item.id == row.id;
      });
      this.subCourseList.splice(index, 1);
    },
    handleRemove(file,uploadFile) {
      this.form.coverPath=null;
      this.imgshow=false;
    },
    handlePreview(file) {
      console.log(file);
    },
    //handleExceed(files, fileList) {
      //this.$message.warning(
        //`当前限制选择3个文件，本次选择了${
          //files.length
        //}个文件，共选择了${files.length + fileList.length}个文件`
      //);
   // },
    beforeRemove(file) {
      return this.$confirm(`确定移除?`);
    },
    resetForm () {
      this.reload()
    }
  }
};
</script>
